package com.crm.system.service.impl.activityManager;

import com.alibaba.fastjson.JSONArray;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.activityManager.CustomerGiftActivityRelation;
import com.crm.model.entity.activityManager.CustomerProductActivityRelation;
import com.crm.model.entity.activityManager.CustomerProductGiftActivity;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.activityManager.CustomerGiftActivityAddQO;
import com.crm.model.qo.activityManager.CustomerProductGiftActivityQO;
import com.crm.model.vo.activityManager.CustomerProductActivityVO;
import com.crm.model.vo.activityManager.CustomerProductGiftActivityContractVO;
import com.crm.model.vo.activityManager.CustomerProductGiftActivityVO;
import com.crm.model.vo.activityManager.CustomerProductGiftDetailVO;
import com.crm.service.activityManager.CustomerGiftActivityRelationDbService;
import com.crm.service.activityManager.CustomerProductActivityDbService;
import com.crm.service.activityManager.CustomerProductActivityRelationDbService;
import com.crm.service.activityManager.CustomerProductGiftActivityDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.system.service.activityManager.CustomerGiftActivityRelationService;
import com.crm.system.service.activityManager.CustomerProductGiftActivityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.xml.bind.v2.TODO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author luojie
 * @date 2021/3/1 14:51
 */
@Service
public class CustomerProductGiftActivityServiceImpl implements CustomerProductGiftActivityService {

    @Autowired
    private CustomerProductGiftActivityDbService customerProductGiftActivityDbService;
    @Autowired
    private CustomerGiftActivityRelationDbService customerGiftActivityRelationDbService;
    @Autowired
    private CustomerProductDbService customerProductDbService;
    @Autowired
    private CustomerProductActivityDbService productActivityDbService;

    /**
     * 活动管理--赠品活动列表分页信息
     * @param productGiftActivityQO    ---赠品列表查询参数
     * @param pageIndex/ pageSize      ---页码、分页大小
     * @param sortName/sortOrder       ---活动列表排序字段及规则
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<CustomerProductGiftActivityVO> selectCustomerProductGiftActivityVOList(CustomerProductGiftActivityQO productGiftActivityQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("createTm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<CustomerProductGiftActivityVO> productGiftActivityVOList = customerProductGiftActivityDbService.selectCustomerProductGiftActivityVOList(productGiftActivityQO,order.toString());
        PageInfo<CustomerProductGiftActivityVO> pageInfo = new PageInfo<CustomerProductGiftActivityVO>(productGiftActivityVOList);
        return new DhPageInfo<CustomerProductGiftActivityVO>(pageInfo, productGiftActivityVOList);
    }

    /**
     * 赠品活动列表--(赠品活动上架时判断)根据赠品活动ID查询活动是否在有效期内
     * @param productGiftActivityId   ---赠品活动ID
     * @Author yincuimei
     * @return
     */
    @Override
    public Boolean selectGiftActivityIsInValidityPeriod(String productGiftActivityId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return customerProductGiftActivityDbService.selectGiftActivityIsInValidityPeriod(productGiftActivityId,dateFormat.format(new Date()));
    }

    /**
     * 赠品活动列表--赠品活动上/下架操作
     * @param productGiftActivityId    ---赠品活动主键
     * @param giftShelfStatus          ---上/下架状态(0:上架;1:下架)
     * @Author yincuimei
     * @return
     */
    @Override
    public Boolean updateGiftActivityShelfStatus(String productGiftActivityId, String giftShelfStatus) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        return customerProductGiftActivityDbService.updateGiftActivityShelfStatus(productGiftActivityId,giftShelfStatus,userAccount.getAccountId());
    }

    /**
     * 赠品活动列表--查看赠品活动
     * @param productGiftActivityId  ---赠品活动ID
     * @param giftCategory           ---赠送类别--1:产品类;2:价格类
     * @Author yincuimei
     * @return
     */
    @Override
    public CustomerProductGiftDetailVO selectCustomerProductGiftActivityDetail(String productGiftActivityId, String giftCategory,String productCategories){
        CustomerProductGiftDetailVO productGiftDetailVO = new CustomerProductGiftDetailVO();
        //1: 查询赠品活动信息(chs_customer_product_gift_activity)
        if("产品类".equals(giftCategory)){//产品类赠品活动
            if("1".equals(productCategories)){
                productGiftDetailVO = customerProductGiftActivityDbService.selectMemberProductCategoryGiftActivityById(productGiftActivityId);
            }else {
                productGiftDetailVO = customerProductGiftActivityDbService.selectNonMemberProductCategoryGiftActivityById(productGiftActivityId);

            }
        }else if("价格类".equals(giftCategory)){//价格类赠品活动
            productGiftDetailVO = customerProductGiftActivityDbService.selectPriceCategoryGiftActivityById(productGiftActivityId);
        }

        //2:根据赠品活动ID查询赠品和赠品活动关系表里的赠品(chs_customer_gift_activity_relation)
        List<CustomerGiftActivityRelation> giftActivityRelationList =  customerGiftActivityRelationDbService.selectGiftDropDownCheckedListByGiftActivityId(productGiftActivityId);

        //3:根据查出的赠品ID去产品表查询其赠品信息(chs_customer_product)
        List<HashMap> productActivityList = new ArrayList<HashMap>();
        giftActivityRelationList.stream().forEach(customerGiftActivityRelation -> {
            HashMap hashMap = new HashMap();
            String productId = customerGiftActivityRelation.getCustomerProductId();
            CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(productId);
            hashMap.put("productId",productId);//赠品ID
            hashMap.put("productName",customerProduct.getProductName());//赠品名称
            productActivityList.add(hashMap);
        });
        if(productActivityList != null && productActivityList.size() > 0){
            productGiftDetailVO.setCustomerProductGiftList(productActivityList);//赠品信息
        }
        return productGiftDetailVO;
    }

    /**
     * 赠品活动列表--删除赠品活动
     * @param productGiftActivityId ---赠品活动ID
     * @Author yincuimei
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public void deleteCustomerProductGiftActivity(String productGiftActivityId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息

        //1: 删除赠品活动表(chs_customer_product_gift_activity将删除状态置为1)
        CustomerProductGiftActivity customerProductGiftActivity = new CustomerProductGiftActivity();
        customerProductGiftActivity.setProductGiftActivityId(productGiftActivityId);//赠品活动ID
        customerProductGiftActivity.setUpdatePeopleId(userAccount.getAccountId()); //当前登录人账号ID
        customerProductGiftActivity.setUpdateTm(new Date());//更新时间
        customerProductGiftActivity.setDeleteStatus((short) StatusCodeEnum.DELETE_CODE.getState());//删除状态--0:正常;1:已删除
        customerProductGiftActivityDbService.deleteCustomerProductActivityById(customerProductGiftActivity);

        //查出赠品活动表下的全部赠品，进行删除
        List<CustomerGiftActivityRelation> customerGiftActivityRelationList = customerGiftActivityRelationDbService.selectGiftDropDownCheckedListByGiftActivityId(productGiftActivityId);
        customerGiftActivityRelationList.stream().forEach(customerGiftActivityRelation -> {
            CustomerGiftActivityRelation giftActivityRelation = new CustomerGiftActivityRelation();
            giftActivityRelation.setGiftActivityRelationId(customerGiftActivityRelation.getGiftActivityRelationId());
            giftActivityRelation.setDeleteStatus((short) StatusCodeEnum.DELETE_CODE.getState());
            customerGiftActivityRelationDbService.deleteCustomerGiftActivityRelationByCustomerGiftActivity(giftActivityRelation);
        });

    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public int addProductGiftActivity(CustomerGiftActivityAddQO customerGiftActivityAddQO) {
        int result = 0;
        //判断赠品活动是否重复
        Boolean repeatResult = customerProductGiftActivityDbService.selectCustomerProductGiftIsRepeat(customerGiftActivityAddQO.getGiftActivityName(),customerGiftActivityAddQO.getProductGiftActivityId());
        if(repeatResult){
            //赠品重复
            return 1;
        }
        String productGiftActivityId = CommonUtils.getGUID();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerProductGiftActivity customerProductGiftActivity = new CustomerProductGiftActivity();
        customerProductGiftActivity.setProductGiftActivityId(productGiftActivityId);
        customerProductGiftActivity.setGiftActivityName(customerGiftActivityAddQO.getGiftActivityName());
        customerProductGiftActivity.setGiftCategory(customerGiftActivityAddQO.getGiftCategory());
        customerProductGiftActivity.setGiftActivityPriceStart(customerGiftActivityAddQO.getGiftActivityPriceStart());
        customerProductGiftActivity.setGiftActivityPriceEnd(customerGiftActivityAddQO.getGiftActivityPriceEnd());
        customerProductGiftActivity.setGiftPeriodValidityStart(customerGiftActivityAddQO.getGiftPeriodValidityStart());
        customerProductGiftActivity.setGiftPeriodValidityEnd(customerGiftActivityAddQO.getGiftPeriodValidityEnd());
        customerProductGiftActivity.setExchangeMethod(customerGiftActivityAddQO.getExchangeMethod());
        customerProductGiftActivity.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        customerProductGiftActivity.setCreatePeopleId(userAccount.getAccountId());
        customerProductGiftActivity.setCreateTm(new Date());
        customerProductGiftActivity.setUpdatePeopleId(userAccount.getAccountId());
        customerProductGiftActivity.setUpdateTm(new Date());
        customerProductGiftActivity.setCustomerProductId(customerGiftActivityAddQO.getCustomerProductId());
        customerProductGiftActivity.setProductCategories(customerGiftActivityAddQO.getProductCategories());

        if(StringUtils.isBlank(customerGiftActivityAddQO.getProductGiftActivityId())){
            //赠品表添加数据
            customerProductGiftActivity.setGiftShelfStatus("0");
            customerProductGiftActivityDbService.insertCustomerProductGiftActivity(customerProductGiftActivity);
        }else {
            //编辑赠品表
            productGiftActivityId = customerGiftActivityAddQO.getProductGiftActivityId();
            customerProductGiftActivity.setProductGiftActivityId(productGiftActivityId);
            customerProductGiftActivity.setUpdatePeopleId(userAccount.getAccountId());
            customerProductGiftActivity.setUpdateTm(new Date());
            customerProductGiftActivityDbService.editProductGiftActivity(customerProductGiftActivity);

            //根据赠品活动id删除赠品对应关系
            CustomerGiftActivityRelation customerGiftActivityRelation = new CustomerGiftActivityRelation();
            customerGiftActivityRelation.setGiftActivityRelationId(productGiftActivityId);
            customerGiftActivityRelation.setDeleteStatus((short) StatusCodeEnum.DELETE_CODE.getState());
            customerGiftActivityRelationDbService.deleteCustomerGiftActivityRelationByCustomerGiftActivity(customerGiftActivityRelation);
        }

        //添加赠品对应关系
        List<String> giftIdList = customerGiftActivityAddQO.getGiftIdList();
        addCustomerGiftActivityRelation(productGiftActivityId,giftIdList,userAccount.getAccountId());
        return result;
    }

    @Override
    public CustomerProductGiftActivity selectCustomerProductGiftActivityById(String productGiftActivityId) {
        CustomerProductGiftActivity customerProductGiftActivity = customerProductGiftActivityDbService.selectProductGiftActivityById(productGiftActivityId);
        return customerProductGiftActivity;
    }

    @Override
    public int editProductGiftActivity(CustomerGiftActivityAddQO customerGiftActivityAddQO) {
        int result = 0;
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //判断赠品活动是否重复
        Boolean repeatResult = customerProductGiftActivityDbService.selectCustomerProductGiftIsRepeat(customerGiftActivityAddQO.getGiftActivityName(),customerGiftActivityAddQO.getProductGiftActivityId());
        if(repeatResult){
            result = 1;
        }
        //编辑赠品活动
        String productGiftActivityId = customerGiftActivityAddQO.getProductGiftActivityId();
        CustomerProductGiftActivity customerProductGiftActivity = new CustomerProductGiftActivity();
        customerProductGiftActivity.setProductGiftActivityId(customerGiftActivityAddQO.getProductGiftActivityId());
        customerProductGiftActivity.setGiftActivityName(customerGiftActivityAddQO.getGiftActivityName());
        customerProductGiftActivity.setGiftCategory(customerGiftActivityAddQO.getGiftCategory());
        customerProductGiftActivity.setGiftActivityPriceStart(customerGiftActivityAddQO.getGiftActivityPriceStart());
        customerProductGiftActivity.setGiftActivityPriceEnd(customerGiftActivityAddQO.getGiftActivityPriceEnd());
        customerProductGiftActivity.setGiftPeriodValidityStart(customerGiftActivityAddQO.getGiftPeriodValidityStart());
        customerProductGiftActivity.setGiftPeriodValidityEnd(customerGiftActivityAddQO.getGiftPeriodValidityEnd());
        customerProductGiftActivity.setExchangeMethod(customerGiftActivityAddQO.getExchangeMethod());
        customerProductGiftActivity.setUpdatePeopleId(userAccount.getAccountId());
        customerProductGiftActivity.setUpdateTm(new Date());
        Boolean updateResult = customerProductGiftActivityDbService.editProductGiftActivity(customerProductGiftActivity);

        //根据赠品活动id删除赠品对应关系
        CustomerGiftActivityRelation customerGiftActivityRelation = new CustomerGiftActivityRelation();
        customerGiftActivityRelation.setGiftActivityRelationId(productGiftActivityId);
        customerGiftActivityRelation.setDeleteStatus((short) StatusCodeEnum.DELETE_CODE.getState());
        customerGiftActivityRelationDbService.deleteCustomerGiftActivityRelationByCustomerGiftActivity(customerGiftActivityRelation);
        //新增赠品对应关系
        List<String> giftIdList = customerGiftActivityAddQO.getGiftIdList();
        addCustomerGiftActivityRelation(productGiftActivityId,giftIdList,userAccount.getAccountId());
        return result;
    }

    /**
     * 添加赠品活动和更新赠品活动时插入赠品活动和赠品的对应关系
     * @param productGiftActivityId
     * @param giftIdList
     * @param updatePeopleId
     * @return
     */
    public Boolean addCustomerGiftActivityRelation(String productGiftActivityId,List<String> giftIdList,String updatePeopleId){
        giftIdList.stream().forEach(giftId ->{
            CustomerGiftActivityRelation customerGiftActivityRelation = new CustomerGiftActivityRelation();
            customerGiftActivityRelation.setGiftActivityRelationId(CommonUtils.getGUID());
            customerGiftActivityRelation.setProductGiftActivityId(productGiftActivityId);
            customerGiftActivityRelation.setCustomerProductId(giftId);
            customerGiftActivityRelation.setCreatePeopleId(updatePeopleId);
            customerGiftActivityRelation.setCreateTm(new Date());
            customerGiftActivityRelation.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            customerGiftActivityRelationDbService.insertCustomerGiftActivityRelation(customerGiftActivityRelation);
        });
        return true;
    }

    @Override
    public List<HashMap> selectProductDropDownCheckedListByProductId(String productId) {
        List<HashMap> hashMapList = new ArrayList<HashMap>();
        List<CustomerProduct> customerProductList = customerProductDbService.selectProductDropDownList("");
        for (CustomerProduct customerProduct : customerProductList) {
            HashMap hashMap = new HashMap();
            //判断产品id相同的把checked设置为true
            if(productId.equals(customerProduct.getCustomerProductId())){
                hashMap.put("productId",productId);
                hashMap.put("productName",customerProduct.getProductName());
                hashMap.put("checked",true);
            }else {
                hashMap.put("productId",productId);
                hashMap.put("productName",customerProduct.getProductName());
                hashMap.put("checked",false);
            }
            hashMapList.add(hashMap);
        }
        return hashMapList;
    }

    @Override
    public List<CustomerProductGiftActivityContractVO> selectProductGiftListByProductIdAndPrice(JSONArray selectProductGiftListByProductIdList, BigDecimal price) {
        //把全部产品id "1"放进selectProductGiftListByProductIdList
        selectProductGiftListByProductIdList.add("1");
        List<CustomerProductGiftActivityContractVO> customerProductGiftActivityVOList = customerProductGiftActivityDbService.selectProductGiftListByProductIdAndPrice(selectProductGiftListByProductIdList,price);
        customerProductGiftActivityVOList.stream().forEach(customerProductGiftActivityContractVO -> {
            //查询产品类或者价格类中文返回给前端
            if("1".equals(customerProductGiftActivityContractVO.getGiftCategory())){
                customerProductGiftActivityContractVO.setGiftCategoryName("产品类");
            }else{
                customerProductGiftActivityContractVO.setGiftCategoryName("价格类");
            }
            List<HashMap> productList = new ArrayList<HashMap>();
            String productGiftActivityId = customerProductGiftActivityContractVO.getProductGiftActivityId();
            //查询赠品活动下的赠品列表
            List<CustomerGiftActivityRelation> customerGiftActivityRelationList = customerGiftActivityRelationDbService.selectGiftDropDownCheckedListByGiftActivityId(productGiftActivityId);
            for (CustomerGiftActivityRelation customerGiftActivityRelation : customerGiftActivityRelationList) {
                CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(customerGiftActivityRelation.getCustomerProductId());
                HashMap map = new HashMap();
                map.put("productId",customerProduct.getCustomerProductId());
                map.put("productName",customerProduct.getProductName());
                map.put("productOriginalPrice",customerProduct.getProductOriginalPrice());
                map.put("productUnitPrice",customerProduct.getProductUnitPrice());
                //赠品列表全是非会员产品
                map.put("productCategories","0");
                productList.add(map);
            }
            customerProductGiftActivityContractVO.setGiftProductList(productList);
        });
        return customerProductGiftActivityVOList;
    }
}
